package com.wangyadong.hobby.concurrent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;

public class CountDownLatchDemo {

    private static final CountDownLatch latch = new CountDownLatch(10);
    public static final Consumer<String> PRINT_CONSUMER = (s) -> {
        System.out.println(Thread.currentThread().getName() + s);
    };

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            final int index = i;
            new Thread(() -> {
                try {
                    PRINT_CONSUMER.accept("--------------子任务开始执行----------------");
                    if (index % 6 == 0) {
                        Thread.currentThread().interrupt();
                    }
                    TimeUnit.SECONDS.sleep(2);
                    PRINT_CONSUMER.accept("--------------子任务开始执行完毕-------------");
                } catch (InterruptedException e) {
                    PRINT_CONSUMER.accept("--------------发生异常----------------");
                } finally {
                    latch.countDown();
                }
            }).start();
        }
        latch.await();
        assert latch.getCount() == 0;
        System.out.println("结束");
    }

    public static final Function<Thread, String> getThreadName = (t) -> t.getName();


}
